package cn.edu.lingnan.lsqn.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import cn.cdahua.basic.dao.BaseDao;
import cn.cdahua.basic.model.Pager;
import cn.edu.lingnan.lsqn.model.Group;
import cn.edu.lingnan.lsqn.model.Role;
import cn.edu.lingnan.lsqn.model.User;
import cn.edu.lingnan.lsqn.model.UserGroup;
import cn.edu.lingnan.lsqn.model.UserRole;

@SuppressWarnings("unchecked")
@Repository("userDao")
public class UserDao extends BaseDao<User> implements IUserDao {

	@Override
	public void addUserRole(User user, Role role) {
		this.getSession().save(new UserRole(user, role));
	}

	@Override
	public void addUserGroup(User user, Group group) {
		UserGroup userGroup = new UserGroup(user, group);
		this.getSession().save(userGroup);
	}

	@Override
	public User loadByName(String username) {
		String hql = "from User u where u.username = ?";
		return loadByHql(hql, username);
	}
	@Override
	public User loadByEmail(String email) {
		String hql = "from User u where u.email = ?";
		return loadByHql(hql, email);
	}

	@Override
	public List<User> list() {
		String hql = "from User";
		return this.list(hql);
	}

	@Override
	public Pager<User> find() {
		String hql = "from User";
		return this.find(hql);
	}

	@Override
	public List<Group> listUserGroup(int id) {
		String hql = "select ug.group from UserGroup ug where ug.user.id = ?";
		hql = setOrder(hql);
		return this.getSession().createQuery(hql).setParameter(0, id).list();
	}

	@Override
	public List<Role> listUserRole(int id) {
		String hql = "select ur.role from UserRole ur where ur.user.id=?";
		hql = setOrder(hql);
		return this.getSession().createQuery(hql).setParameter(0, id).list();
	}

	@Override
	public List<Integer> listUserRoleIds(int id) {
		String hql = "select ur.role.id from UserRole ur where ur.user.id=?";
		hql = setOrder(hql);
		return this.getSession().createQuery(hql).setParameter(0, id).list();
	}

	@Override
	public List<Integer> listUserGroupIds(int id) {
		String hql = "select ug.group.id from UserGroup ug where ug.user.id = ?";
		hql = setOrder(hql);
		return this.getSession().createQuery(hql).setParameter(0, id).list();
	}

	@Override
	public Pager<User> listUserByGroup(int g_id) {
		String hql = "select ug.user from UserGroup ug where ug.group.id = ?";
		return find(hql, g_id);
	}

	@Override
	public Pager<User> listUserByRole(int r_id) {
		String hql = "select ur.user from UserRole ur where ur.role.id = ?";
		return find(hql,r_id);
	}

	@Override
	public void deleteUsergroupById(int id) {
		String hql = "delete UserGroup ug where ug.group.id = ?";
		updateByHql(hql,id);
	}

	@Override
	public void deleteUserroleById(int id) {
		String hql = "delete UserRole ug where ug.role.id = ?";
		updateByHql(hql,id);
	}

}
